﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ecopsy.DataTier;
using AgencyEntityLib.Context;

namespace AgencyEntityLib.BaseEntity
{
    /// <summary>
    /// Агентство 
    /// </summary>
    public class Agency : Face_U, ISqlSignature
    {
        #region Properties
        private EntityList  _DictionarySettings = new EntityList ();
        /// <summary>
        /// Карта справочников, 
        /// В списке преречень собственных типов справочников. 
        /// </summary>
        public EntityList DictionarySettings { get { return _DictionarySettings; } set { _DictionarySettings = value; } }
        
        private EntityList _AdressPrograms = new EntityList();
        /// <summary>
        /// Доступные агентсву адресные программы
        /// </summary>
        public EntityList AdressPrograms { get { return _AdressPrograms; } set { _AdressPrograms = value; } }
                
        //Департаменты
        private Department  _Departments = new Department ();
        /// <summary>
        /// Дерево оргструктуры
        /// </summary>
        public Department Department { get { return _Departments; } set { _Departments = value; } }
        
        public EntityList _SurfaceGroups = new EntityList();
        /// <summary>
        /// ID Группы поверхностей
        /// </summary>
        public EntityList SurfaceGroups { get { return _SurfaceGroups; } set { _SurfaceGroups = value; } }

        public EntityList _Discounts = new EntityList();
        /// <summary>
        /// Скидки
        /// </summary>
        public EntityList Discounts { get { return _Discounts; } set { _Discounts = value; } }

        
        private SiteMap _SiteMap = new SiteMap();

        /// <summary>
        /// карта распределения доступа к страничкам по ролям
        /// </summary>
        public SiteMap SitMap { get { return _SiteMap; } set { _SiteMap = value; } }


        private FilterList _FilterList = new FilterList();
        /// <summary>
        /// список общих фиьтров агенства
        /// </summary>
        public FilterList FilterList 
        {
            get { return _FilterList ;}
            set { _FilterList=value ;}

        }

        /// <summary>
        /// Хранилище переопределенных фабрик классов
        /// </summary>
        private WS_FactoryList _WS_FactoryList = new WS_FactoryList();
        public WS_FactoryList WS_FactoryList { get { return _WS_FactoryList; } }
        #endregion 

        #region Methods
        /// <summary>
        /// Установить движок бизнес правил для запрашиваемого объекта
        /// </summary>
        /// <param name="Instance"></param>
        /// <param name="BRE"></param>
        public void SetBusinesRulesEngine(BusinessRulesEntity Instance, ref BusinesRulesEngine BRE)
        {
            if (Instance is Contract && (null == BRE))
            {

                BRE = new Contract_BusinesRulesEngine() { Owner = Instance };

            }

            if (Instance is ContractSurfaceItem && (null == BRE))
            {
                BRE = new Contract_BusinesRulesEngine() { Owner = Instance };

            }



            if (Instance is Constraction && (null == BRE))
            {
                BRE = new Constraction_BusinesRulesEngine() { Owner = Instance };

            }

        }

        /// <summary>
        /// найти депатамент
        /// </summary>
        /// <param name="_Agency"></param>
        /// <param name="DepartmentID"></param>
        /// <returns></returns>
        public Department GetDepartment(string DepartmentID)
        {
            Department res = null;
            Func<Department, bool> IsIm = delegate(Department CurrentDepartment)
            {
                bool isOk = (CurrentDepartment.ID == DepartmentID);
                if (isOk) res = CurrentDepartment;
                return isOk;
            };
            NextDeparment(Department, IsIm);
            return res;
        }

        /// <summary>
        /// Вернуть сотрудников указанного департамента - если WitchChild - с дочерними депратаментами
        /// </summary>
        /// <param name="WitchChild"></param>
        /// <param name="DepartmentID"></param>
        /// <returns></returns>
        public List<Employeer> GetEmplList(bool WitchChild, Department _Department)
        {
            if (!WitchChild) return _Department.GetEmployeers();

            List<Employeer> res = new List<Employeer>();
            Func<Department, bool> GetEmpl = delegate(Department CurrentDepartment)
            {
                res.AddRange(CurrentDepartment.GetEmployeers());
                return false;
            };
            NextDeparment(_Department, GetEmpl);
            return res;
        }


        public  List<AdressPropramItem> GetAdressPropramItems()
        {
            TreeDictionaryItem[] items = AgencyLib_GlobalConstants.TreeDictionaryContext.GetAdressProgrammAsArray();
            List<AdressPropramItem> res = new List<AdressPropramItem>();

            foreach (TreeDictionaryItem item in items)
            {
                bool sel = (AdressPrograms[item.ID] != null);
                AdressPropramItem i = new AdressPropramItem() { ID = item.ID, Name = item.Name, Selected = sel};
                res.Add(i);
            }

            return res;

        }
        public  void Set_UseAdressProgramm( string TreeDictionaryID, bool value)
        {

            bool b = value;
            if (b)
            {
                AdressPrograms.Remove(TreeDictionaryID);
                AdressPrograms.Add(new EntitySingle() { ID = TreeDictionaryID });
            }
            else
                AdressPrograms.Remove(TreeDictionaryID);

        }

        /// <summary>
        /// Возвращеает истину если в настройках - использовать системную папку справочника
        /// </summary>
        /// <param name="?"></param>
        /// <param name="TreeDictionaryID"></param>
        public  bool CheckSetting_UseSystemDictionary( string TreeDictionaryID)
        {
            DictionarySettings.Reset();
            return (DictionarySettings[TreeDictionaryID] == null);
        }


        #endregion
    
        #region Tools
        private void NextDeparment(Department d, Func<Department, bool> f)
        {
            if (null == d)
                return;

            if (f(d)) return;
            foreach (Department item in d.ChildNodes)
            {
                NextDeparment(item, f);
            }
        }
        #endregion

        #region Override
        protected override string TagName
        {
            get
            {
                return "Agency";
            }
        }

        public override string AgencyID
        {
            get
            {
                return ID;
            }
        }
        #endregion

        #region ISqlObject Members

        public override string SaveProcedure
        {
            get
            {
               return "AgencySave"; 
            }
        }

        public override string DeleteProcedure
        {
            get
            {
                return "AgencyDelete";
            }
        }

        public override string LoadProcedure
        {
            get
            {
                return "AgencyLoad"; 
            }
        } 
        
        

        #endregion

    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Коллекция содержить только переопределенные фабрики
    /// Если нет переопределенной - возвращает стандартную
    /// </summary>
    public class WS_FactoryList : EntityList
    {
        public const string wsKey_Agency            = "Agency";
        public const string wsKey_Face              = "Face";
        public const string wsKey_Contract          = "Contract";
        public const string wsKey_Constraction      = "Constraction";
        public const string wsKey_Task              = "Task";
        public const string wsKey_Dictionary        = "Dictionary";
        public const string wsKey_BusinesEngine     = "BusinesEngine";
        

        public override EntitySingle this[object KeyValue]
        {
            get
            {
                EntitySingle obj = base[KeyValue];
                if (null != obj)
                    return obj;

                switch (KeyValue.ToString())
                {
                    case wsKey_Agency:
                        return new wsAgency();
                    case wsKey_Face:
                        return new wsFace();
                    case wsKey_Contract:
                        return new wsContract();
                    case wsKey_Task:
                        return new wsTask();
                    case wsKey_Dictionary:
                        return new wsDictionary();
                    case wsKey_Constraction:
                        return new wsConstractions();
                    
                    case wsKey_BusinesEngine :                         
                        return new wsBusinesEngine ();
                        
                    

                    default:
                        return null;
                }
            }
        }

    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// адресные программы доступные агенству
    /// </summary>
    public class AdressPropramItem
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public bool Selected { get; set; }
        public DateTime CreateDate { get; set; }
        public DateTime LastUpdate { get; set; }

    }
    
}

